package failover

import (
	"context"
	"errors"
	"sync/atomic"
	"webook/sms/service"
)

type FailoverSMSService struct {
	// 一大堆可供选择的 SMS Service 实现
	svcs []service.Service

	idx uint64
}

func NewFailoverSMSService(svc []service.Service) *FailoverSMSService {
	return &FailoverSMSService{
		svcs: svc,
	}
}

func (f *FailoverSMSService) Send(ctx context.Context, tplId string, args []string, number ...string) error {
	for _, svc := range f.svcs {
		err := svc.Send(ctx, tplId, args, number...)
		if err == nil {
			return nil
		}
	}
	return errors.New("发送失败，所有服务商都尝试了")
}

func (f *FailoverSMSService) SendV1(ctx context.Context, tplId string, args []string, number ...string) error {
	// 先把下标往后推一位
	idx := atomic.AddUint64(&f.idx, 1)
	length := uint64(len(f.svcs))

	for i := idx; i < idx+length; i++ {
		svc := f.svcs[i%length]
		err := svc.Send(ctx, tplId, args, number...)
		switch err {
		case nil:
			return nil
		case context.DeadlineExceeded, context.Canceled:
			return err
		}
		// 其他情况会走这里，打印日志
	}
	return errors.New("发送失败，所有服务商都尝试过")
}
